package cn.hdu.liang.core.controller;

import cn.hdu.liang.common.web.session.SessionProvider;
import cn.hdu.liang.core.bean.BuyCart;
import cn.hdu.liang.core.bean.BuyItem;
import cn.hdu.liang.core.bean.product.Sku;
import cn.hdu.liang.core.bean.user.Addr;
import cn.hdu.liang.core.bean.user.Buyer;
import cn.hdu.liang.core.query.user.AddrQuery;
import cn.hdu.liang.core.service.product.SkuService;
import cn.hdu.liang.core.service.user.AddrService;
import cn.hdu.liang.core.web.Constants;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

@Controller
public class CartController {

    @Autowired
    private SkuService skuService;
    @Autowired
    private AddrService addrService;
    @Autowired
    private SessionProvider sessionProvider;

    //购买按钮
    @RequestMapping(value = "/shopping/buyCart.shtml")
    public String buyCart(Integer skuId, Integer amount, Integer buyLimit, Integer productId, HttpServletRequest req, HttpServletResponse resp, ModelMap model) {

        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
        BuyCart buyCart = null;

        //判断Cookie里面有购物车
        Cookie[] cookies = req.getCookies();
        if(cookies != null && cookies.length > 0) {
            for(Cookie c : cookies) {
                if(Constants.BUYCART_COOKIE.equals(c.getName())) {
                    String value = c.getValue();
                    try {
                        buyCart = om.readValue(value.toString(), BuyCart.class);
                    } catch(IOException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
        //购物车
        if(buyCart == null) {
            buyCart = new BuyCart();
        }

        if(skuId != null) {
            Sku sku = new Sku();
            sku.setId(skuId);
            if(buyLimit != null) {
                sku.setSkuUpperLimit(buyLimit);
            }

            //创建购物项
            BuyItem buyItem = new BuyItem();
            buyItem.setSku(sku);
            buyItem.setAmount(amount);

            buyCart.addItem(buyItem);
            if(productId != null) {
                buyCart.setProductId(productId);
            }

            //购物车对象转Json
            //对象转Json  写过程
            StringWriter json = new StringWriter();
            try {
                om.writeValue(json, buyCart);
            } catch(IOException e) {
                e.printStackTrace();
            }

            //购物车装进Cookie
            Cookie cookie = new Cookie(Constants.BUYCART_COOKIE, json.toString());
            //关闭浏览器也要有Cookie
            cookie.setMaxAge(3600 * 24);
            cookie.setPath("/");
            resp.addCookie(cookie);
        }

        //把购物车装满
        List<BuyItem> items = buyCart.getItems();
        for(BuyItem item : items) {
            Sku s = skuService.getSkuByKey(item.getSku().getId());
            item.setSku(s);
        }

        //添加属性
        model.addAttribute("buyCart", buyCart);
        return "product/cart";
    }


    //清空购物车
    @RequestMapping(value = "/shopping/clearCart.shtml")
    public String clearCart(HttpServletRequest req, HttpServletResponse resp) {

        Cookie cookie = new Cookie(Constants.BUYCART_COOKIE, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        resp.addCookie(cookie);

        return "redirect:/shopping/buyCart.shtml";
    }

    @RequestMapping(value = "/shopping/deleteItem.shtml")
    public String deleteItem(HttpServletRequest req, Integer skuId, HttpServletResponse resp) {
        //springmvc
        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

        //声明
        BuyCart buyCart = null;
        //判断Cookie是否有购物车
        Cookie[] cookies = req.getCookies();
        if(null != cookies && cookies.length > 0) {
            for(Cookie c : cookies) {
                if(Constants.BUYCART_COOKIE.equals(c.getName())) {
                    //如果有了  就使用此购物车
                    String value = c.getValue();
                    //
                    try {
                        buyCart = om.readValue(value, BuyCart.class);
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }

        if(null != buyCart) {

            Sku sku = new Sku();
            sku.setId(skuId);
            //创建购物项
            BuyItem buyItem = new BuyItem();
            buyItem.setSku(sku);
            buyCart.deleteItem(buyItem);

            //流
            StringWriter json = new StringWriter();
            //对象转Json  写的过程  Json是字符串流
            try {
                om.writeValue(json, buyCart);
            } catch(Exception e) {
                e.printStackTrace();
            }
            //购物车装进Cookie中   对象转Json
            Cookie cookie = new Cookie(Constants.BUYCART_COOKIE, json.toString());
            cookie.setMaxAge(3600 * 24);
            cookie.setPath("/");
            //发送
            resp.addCookie(cookie);
        }
        return "redirect:/shopping/buyCart.shtml";
    }

    //结算
    @RequestMapping(value = "/buyer/trueBuy.shtml")
    public String trueBuy(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        //springmvc
        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

        BuyCart buyCart = null;
        Cookie[] cookies = request.getCookies();
        if(null != cookies && cookies.length > 0) {
            for(Cookie c : cookies) {
                if(Constants.BUYCART_COOKIE.equals(c.getName())) {
                    //如果有了  就使用此购物车
                    String value = c.getValue();
                    try {
                        buyCart = om.readValue(value, BuyCart.class);
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
        //判断购物车中是否有商品
        if(null != buyCart) {
            //判断购物车中的商品是否还有库存
            List<BuyItem> items = buyCart.getItems();
            if(null != items && items.size() > 0) {
                //购物车的商品项
                Integer i = items.size();
                //判断购物车中的商品是否还有库存
                for(BuyItem it : items) {
                    Sku sku = skuService.getSkuByKey(it.getSku().getId());
                    //判断库存
                    if(sku.getStockInventory() < it.getAmount()) {
                        //删除此商品
                        buyCart.deleteItem(it);
                    }
                }
                //清理后商品项个数 l=0
                Integer l = items.size();
                //判断清理前后
                if(i > l) {
                    //修改Cookie中的购物车数据
                    StringWriter json = new StringWriter();
                    try {
                        om.writeValue(json, buyCart);
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                    //购物车装进Cookie中   对象转Json
                    Cookie cookie = new Cookie(Constants.BUYCART_COOKIE, json.toString());
                    cookie.setMaxAge(60 * 60 * 24);
                    cookie.setPath("/");
                    //发送
                    response.addCookie(cookie);

                    return "redirect:/shopping/buyCart.shtml";
                } else {
                    //收货地址加载
                    Buyer buyer = (Buyer) sessionProvider.getAttribute(request, Constants.BUYER_SESSION);
                    AddrQuery addrQuery = new AddrQuery();
                    addrQuery.setBuyerId(buyer.getUsername());
                    addrQuery.setIsDef(1); //默认是1

                    List<Addr> addrs = addrService.getAddrList(addrQuery);
                    model.addAttribute("addr", addrs.get(0));
                    //装购物车装满
                    List<BuyItem> its = buyCart.getItems();
                    for(BuyItem item : its) {
                        Sku s = skuService.getSkuByKey(item.getSku().getId());
                        item.setSku(s);
                    }
                    model.addAttribute("buyCart", buyCart);
                    //正常
                    return "product/productOrder";
                }

            } else {
                return "redirect:/shopping/buyCart.shtml";
            }
        } else {
            return "redirect:/shopping/buyCart.shtml";
        }
    }

}
